package com.lechi.web.job;

import com.lechi.iot.netty.channel.ITcpChannel;
import com.lechi.iot.netty.message.TcpByteArrayMessage;
import com.lechi.iot.netty.message.TcpMessage;
import com.lechi.iot.netty.utils.BytesToHexUtil;
import com.lechi.iot.netty.utils.Hex;
import com.lechi.iot.netty.utils.NettyCacheUtils;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.util.ExpireCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * The type Send cmd job.
 *
 * @author yangguang
 */
@Slf4j
public class SendCmdJob implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        final List<Map<String, String>> list = (List<Map<String, String>>) context.getMergedJobDataMap().get("deviceSn:cmd");
        for (Map<String, String> deviceSNAndCmdMap : list) {
            Set<Map.Entry<String, String>> setEntry = deviceSNAndCmdMap.entrySet();
            setEntry.forEach(entry -> {
                final String deviceSN = entry.getKey();
                final String cmd = entry.getValue();
                String hostName = GuavaCacheUtil.getBiDeviceSnAndIPMap().get(deviceSN);
                byte[] sendMsg = BytesToHexUtil.hexStrToBinaryStr(cmd);
                if (cmd.isBlank() || !ObjectUtils.notEqual(deviceSN, hostName)) {
                    log.debug("指令：{} 暂停发送, 设备序列号:{} 没有注册~！", cmd, deviceSN);
                    return;
                }
                ITcpChannel tcpChannel = NettyCacheUtils.get(hostName, ITcpChannel.class);
                if (tcpChannel == null) {
                    log.error("定时轮询任务发送异常，设备地址：{} 获取tcpChannel值为空， 请联系工程师解决！", hostName);
                    return;
                }
                TcpMessage message = new TcpByteArrayMessage(sendMsg);
                log.debug("轮询任务待下发设备：{}，设备地址：{}， 指令数据：{}", deviceSN, hostName, Hex.toHexString(message.toBytes()));
                tcpChannel.send(message);
            });
        }
    }
}